package net.koodar.forge.business.category.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import net.koodar.forge.business.category.model.dto.CategoryParamDTO;
import net.koodar.forge.business.category.model.dto.CategoryQueryDTO;
import net.koodar.forge.business.category.model.entity.Category;
import net.koodar.forge.business.category.model.entity.CategoryAttribute;
import net.koodar.forge.business.category.model.entity.CategoryAttributeValue;
import net.koodar.forge.business.category.manager.CategoryAttributeManager;
import net.koodar.forge.business.category.manager.CategoryAttributeValueManager;
import net.koodar.forge.business.category.manager.CategoryManager;
import net.koodar.forge.common.code.UserErrorCode;
import net.koodar.forge.common.domain.dto.MultiResponse;
import net.koodar.forge.common.domain.dto.Response;
import net.koodar.forge.common.domain.dto.SingleResponse;
import net.koodar.forge.mybatis.util.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类接口实现类
 * <p>
 * @author liyc
 */
@Service
@RequiredArgsConstructor
public class CategoryService {

    private final CategoryManager categoryManager;
    private final CategoryAttributeManager categoryAttributeManager;
    private final CategoryAttributeValueManager categoryAttributeValueManager;

    public Response listTree() {
        List<Category> categoryList = categoryManager.list();

        // 获取根节点
        List<Category> rootCategoryList = categoryList
                .stream()
                .filter(category -> category.getParentId() == null)
                .toList();

        // 转换为Tree结构
        List<Category> toTree = toTree(rootCategoryList, categoryList);

        return MultiResponse.ok(toTree);
    }

    public Response getCategoryById(Long id) {
        Category category = categoryManager.findById(id);
        List<Category> children = categoryManager.findByParentId(id);
        category.setChildren(children);

        // 获取分类属性
        List<CategoryAttribute> attributeList = categoryAttributeManager.findByCategoryId(id);
        category.setAttributeList(attributeList);
        // 获取分类属性值
        List<Long> attributeIdList = attributeList.stream().map(CategoryAttribute::getId).toList();
        List<CategoryAttributeValue> attributeValueList = categoryAttributeValueManager.findByAttributeIds(attributeIdList);
        attributeValueList.forEach(attributeValue -> {
            attributeList.forEach(attribute -> {
                if (attribute.getId().equals(attributeValue.getAttributeId())) {
                    if (attribute.getAttributeValueList() == null) {
                        attribute.setAttributeValueList(new ArrayList<>());
                    }
                    attribute.getAttributeValueList().add(attributeValue);
                }
            });
        });
        return SingleResponse.ok(category);
    }

    public Response pageCategory(CategoryQueryDTO categoryQueryDTO) {
        Page<Category> categoryPage = categoryManager.page(categoryQueryDTO.toPage(), categoryQueryDTO.toQueryWrapper());
        List<Category> records = categoryPage.getRecords();
        return SingleResponse.ok(PageUtil.toPage(records, categoryPage.getTotal()));
    }

    @Transactional(rollbackFor = Exception.class)
    public Response addCategory(CategoryParamDTO categoryParamDTO) {
        Category dbCategory = categoryManager.findByParentIdAndCode(categoryParamDTO.getParentId(), categoryParamDTO.getCode());
        if (dbCategory != null) {
            return SingleResponse.error(UserErrorCode.ALREADY_EXIST, "分类编码已存在");
        }
        Category category = categoryParamDTO.toEntity();
        categoryManager.save(category);

        // 保存分类属性
        List<CategoryAttribute> attributeList = category.getAttributeList();
        if (attributeList != null && !attributeList.isEmpty()) {
            attributeList.forEach(attribute -> attribute.setCategoryId(category.getId()));
            categoryAttributeManager.saveBatch(attributeList);

            // 保存分类属性值
            for (CategoryAttribute categoryAttribute : attributeList) {
                List<CategoryAttributeValue> attributeValueList = categoryAttribute.getAttributeValueList();
                if (attributeValueList != null && !attributeValueList.isEmpty()) {
                    attributeValueList.forEach(attributeValue -> attributeValue.setAttributeId(categoryAttribute.getId()));
                    categoryAttributeValueManager.saveBatch(attributeValueList);
                }
            }
        }
        return Response.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Response updateCategory(CategoryParamDTO categoryParamDTO) {
        Category dbCategory = categoryManager.findById(categoryParamDTO.getId());
        if (!dbCategory.getId().equals(categoryParamDTO.getId())) {
            return SingleResponse.error(UserErrorCode.ALREADY_EXIST, "分类编码已存在");
        }

        if (countByParentId(dbCategory.getId()) > 0 && !categoryParamDTO.getSubFlag()) {
            return SingleResponse.error(UserErrorCode.PARAM_ERROR,"分类下存在子分类，不能修改为正常节点");
        }

        Category category = categoryParamDTO.toEntity();
        categoryManager.save(category);

        // 查询分类属性
        List<CategoryAttribute> dbAttributeList = categoryAttributeManager.findByCategoryId(category.getCreatorId());
        // 删除分类属性值
        for (CategoryAttribute categoryAttribute : dbAttributeList) {
            List<CategoryAttributeValue> dbAttributeValueList = categoryAttributeValueManager.findByAttributeId(categoryAttribute.getId());
            categoryAttributeValueManager.removeBatchByIds(dbAttributeValueList);
        }
        // 删除分类属性
        categoryAttributeManager.removeBatchByIds(dbAttributeList);

        // 保存分类属性
        List<CategoryAttribute> attributeList = category.getAttributeList();
        if (attributeList != null && !attributeList.isEmpty()) {
            attributeList.forEach(attribute -> attribute.setCategoryId(category.getId()));
            categoryAttributeManager.saveBatch(attributeList);

            // 保存分类属性值
            for (CategoryAttribute categoryAttribute : attributeList) {
                List<CategoryAttributeValue> attributeValueList = categoryAttribute.getAttributeValueList();
                if (attributeValueList != null && !attributeValueList.isEmpty()) {
                    attributeValueList.forEach(attributeValue -> attributeValue.setAttributeId(categoryAttribute.getId()));
                    categoryAttributeValueManager.saveBatch(attributeValueList);
                }
            }
        }
        return Response.ok();
    }

    public Response deleteCategory(Long id) {
        if (countByParentId(id) > 0) {
            return SingleResponse.error(UserErrorCode.PARAM_ERROR,"分类下存在子分类，不能删除");
        }
        categoryManager.removeById(id);
        return Response.ok();
    }

    public Response disableCategory(Long id) {
        Category category = categoryManager.findById(id);
        category.setStatusFlag(false);
        categoryManager.save(category);
        return Response.ok();
    }

    // 查询商品分类的子分类总条数
    private Long countByParentId(Long parentId) {
        return categoryManager.countByParentId(parentId);
    }

    private List<Category> toTree(List<Category> rootCategoryList, List<Category> categoryList) {

        for (Category category : rootCategoryList) {
            List<Category> children = categoryList.stream().filter(c -> c.getParentId() != null && c.getParentId().equals(category.getId())).toList();
            category.setChildren(children);
            toTree(children, categoryList);
        }

        return rootCategoryList;
    }
}
